//
//  XMChatView.m
//  XMJJ_zml
//
//  Created by 丁浩 on 2025/7/1.
//

#import "XMChatView.h"
#import "XMChatCell.h"
#import "XMChatTextCell.h"
#import "XMChatImgCell.h"
#import "XMChatVoiceCell.h"
#import "XMChatCustomCell.h"
#import "XMMessageSendView.h"
#import "XMChatFucView.h"

@interface XMChatView ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tbl;
@property (nonatomic, strong) XMMessageSendView *msgSendView;
@property (nonatomic, strong) XMChatFucView *funcBgView;

@property (nonatomic, strong) NSMutableArray *msgArr;

@property (nonatomic, strong) NSString *senderAvatarImgStr;
@property (nonatomic, strong) NSString *receiverAvatarImgStr;

@property (nonatomic, assign) BOOL isDrag;

@end

@implementation XMChatView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self creatUI];
    }
    return self;
}

- (void)creatUI {
    [self addSubview:self.navView];
    self.navView.backgroundColor = kColorHEX(0xF7F7F7);
    [self addSubview:self.tbl];
    [self addSubview:self.msgSendView];
    [self addSubview:self.funcBgView];
    [self bringSubviewToFront:self.funcBgView];
}

- (void)setContentWithReceiverName:(NSString *)nickName
                      senderAvatar:(nonnull NSString *)senderAvatarImg
                    receiverAvatar:(nonnull NSString *)receiverImg {
    self.navTitleLabel.textAlignment = NSTextAlignmentLeft;
    self.navTitleLabel.text = nickName;
    _senderAvatarImgStr = senderAvatarImg;
    _receiverAvatarImgStr = receiverImg;
}

- (void)setContentWithMessageArr:(NSArray *)msgArr  {
    NSArray *currentArr = [NSArray arrayWithArray:self.msgArr];
    NSArray *realArr = [[msgArr reverseObjectEnumerator] allObjects];
    [self.msgArr removeAllObjects];
    [self.msgArr addObjectsFromArray:realArr];
    [self.msgArr addObjectsFromArray:currentArr];
    [_tbl reloadData];
}

- (void)registerFirstFond:(UITapGestureRecognizer *)tap {
    [self.msgSendView endEditing:YES];
}

- (void)sendSucessWithMsgArr:(NSArray *)msgArr {
    [self.msgArr addObjectsFromArray:msgArr];
    [_tbl reloadData];
    [_msgSendView sendSuccess];
    NSIndexPath *index = [NSIndexPath indexPathForRow:self.msgArr.count - 1 inSection:0];
    [_tbl scrollToRowAtIndexPath:index atScrollPosition:UITableViewScrollPositionNone animated:YES];
}

//图片拍照等功能显示
- (void)fucViewIshow:(BOOL)isShow {
    XMWeakSelf;
    if (isShow) {
        [UIView animateWithDuration:.3 animations:^{
            weakSelf.msgSendView.y = weakSelf.height - weakSelf.funcBgView.height - weakSelf.msgSendView.height + kBottomLayout;
            weakSelf.funcBgView.y = weakSelf.height - weakSelf.funcBgView.height;
        }];
    }
    else {
        [UIView animateWithDuration:.3 animations:^{
            weakSelf.msgSendView.y = weakSelf.height - weakSelf.msgSendView.height;
            weakSelf.funcBgView.y = weakSelf.height;
        }];
    }
}

#pragma mark - Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _msgArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    V2TIMMessage *message = _msgArr[indexPath.row];
    switch (message.elemType) {
        case V2TIM_ELEM_TYPE_TEXT: {
            CGFloat maxWidth = self.width - (KScaleWidth(44.0) + KScaleWidth(10.0)*2)*2;
            CGFloat width = [message.textElem.text getWidthWithFont:KScaleWidth(14.0)] + KScaleWidth(18.0)*2;
            if (width <= maxWidth) {
                return KScaleWidth(44.0) + KScaleWidth(20.0);
            }
            else {
                CGFloat height = [message.textElem.text getHeightWithFont:KScaleWidth(14.0) withWidth:maxWidth - KScaleWidth(18.0)*2];
                return height + KScaleWidth(10.0)*4;
            }
        }
            break;
        case V2TIM_ELEM_TYPE_IMAGE: {
            return [self getImgHeightWithMsg:message];
//            return KScaleWidth(235.0);
        }
            break;
        case V2TIM_ELEM_TYPE_SOUND: {
            return KScaleWidth(44.0) + KScaleWidth(20.0);
        }
            break;
        case V2TIM_ELEM_TYPE_CUSTOM: {
            return KScaleWidth(235.0) + KScaleWidth(20.0);
        }
            
        default: {
            return 0;
        }
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    V2TIMMessage *message = _msgArr[indexPath.row];
    if (!_isDrag) {
        NSIndexPath *index = [NSIndexPath indexPathForRow:self.msgArr.count - 1 inSection:0];
        [tableView scrollToRowAtIndexPath:index atScrollPosition:UITableViewScrollPositionNone animated:NO];
    }
    switch (message.elemType) {
        case V2TIM_ELEM_TYPE_TEXT: {
            XMChatTextCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XMChatTextCellName"];
            [cell setContentWithMessage:_msgArr[indexPath.row]
                           senderAvatar:_senderAvatarImgStr
                         receiverAvatar:_receiverAvatarImgStr];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
        case V2TIM_ELEM_TYPE_IMAGE: {
            XMChatImgCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XMChatImgCellName" forIndexPath:indexPath];
            [cell setContentWithMessage:_msgArr[indexPath.row]
                           senderAvatar:_senderAvatarImgStr
                         receiverAvatar:_receiverAvatarImgStr];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
        case V2TIM_ELEM_TYPE_SOUND: {
            XMChatVoiceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XMChatVoiceCellName"];
            [cell setContentWithMessage:message
                           senderAvatar:_senderAvatarImgStr
                         receiverAvatar:_receiverAvatarImgStr];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
        case V2TIM_ELEM_TYPE_CUSTOM: {
            XMChatCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XMChatCustomCellName"];
            [cell setContentWithMessage:message
                           senderAvatar:_senderAvatarImgStr
                         receiverAvatar:_receiverAvatarImgStr];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            XMWeakSelf;
            cell.getGiveBlock = ^(NSDictionary * _Nonnull meetDic) {
                if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(getGiveMeetWithMeetInfo:)]) {
                    [weakSelf.delegate getGiveMeetWithMeetInfo:meetDic];
                }
            };
            return cell;
        }
            break;
            
        default:
            break;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.msgSendView endEditing:YES];
    [self fucViewIshow:NO];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    _isDrag = YES;
}

#pragma mark - Init
- (UITableView *)tbl {
    if (!_tbl) {
        _tbl = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavagationBarH, self.width, self.height - kNavagationBarH - KScaleWidth(80.0) - kBottomLayout)];
        _tbl.delegate = self;
        _tbl.dataSource = self;
        _tbl.backgroundColor = kColorHEX(0xF7F7F7);
        _tbl.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tbl registerClass:[XMChatTextCell class] forCellReuseIdentifier:@"XMChatTextCellName"];
        [_tbl registerClass:[XMChatVoiceCell class] forCellReuseIdentifier:@"XMChatVoiceCellName"];
        [_tbl registerClass:[XMChatImgCell class] forCellReuseIdentifier:@"XMChatImgCellName"];
        [_tbl registerClass:[XMChatCustomCell class] forCellReuseIdentifier:@"XMChatCustomCellName"];
        if (@available(iOS 15.0, *)) {
            _tbl.sectionHeaderTopPadding = 0;
        } else {
            _tbl.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            // Fallback on earlier versions
        }
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(registerFirstFond:)];
        [_tbl addGestureRecognizer:tap];
    }
    return _tbl;
}

- (XMMessageSendView *)msgSendView {
    if (!_msgSendView) {
        _msgSendView = [[XMMessageSendView alloc] initWithFrame:CGRectMake(0, self.height - KScaleWidth(80.0) - kBottomLayout, self.width, KScaleWidth(80.0) + kBottomLayout)];
        
        XMWeakSelf;
        _msgSendView.messageSendBlock = ^(NSString * _Nonnull contentStr) {
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(messageSendWithContent:)]) {
                [weakSelf.delegate messageSendWithContent:contentStr];
            }
        };
        _msgSendView.voiceSendBlock = ^(NSString * _Nonnull pathStr) {
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(voiceMsgSendWithPath:)]) {
                [weakSelf.delegate voiceMsgSendWithPath:pathStr];
            }
        };
        _msgSendView.fucSelectBlock = ^(BOOL isShow) {
            [weakSelf fucViewIshow:isShow];
        };
    }
    return _msgSendView;
}

- (XMChatFucView *)funcBgView {
    if (!_funcBgView) {
        _funcBgView = [[XMChatFucView alloc] initWithFrame:CGRectMake(0, self.height, self.width, KScaleWidth(132.0) + kBottomLayout)];
        _funcBgView.backgroundColor = kColorHEX(0xEBE9EA);
        XMWeakSelf;
        _funcBgView.imgSendBlock = ^(NSString * _Nonnull pathStr) {
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(imgMsgSendWithPath:)]) {
                [weakSelf.delegate imgMsgSendWithPath:pathStr];
            }
        };
    }
    return _funcBgView;
}

- (NSMutableArray *)msgArr {
    if (!_msgArr) {
        _msgArr = [NSMutableArray array];
    }
    return _msgArr;
}

- (CGFloat)getImgHeightWithMsg:(V2TIMMessage *)message {
    CGFloat height = 0;
    if (message.isSelf) {
        UIImage *img = [UIImage imageWithContentsOfFile:message.imageElem.path];
        if (img.size.width > img.size.height) {
            if (img.size.width > KScaleWidth(224.0)) {
                height = img.size.height*KScaleWidth(224.0)/img.size.width;
            }
            else {
                height = img.size.height;
            }
        }
        else {
            if (img.size.height > KScaleWidth(224.0)) {
                height = KScaleWidth(224.0);
            }
            else {
                height = img.size.height;
            }
        }
    }
    else {
        V2TIMImage *imgModel = [message.imageElem.imageList lastObject];
        if (imgModel.width > imgModel.height) {
            if (imgModel.width > KScaleWidth(224.0)) {
                height = imgModel.height*KScaleWidth(224.0)/imgModel.width;
            }
            else {
                height = imgModel.height;
            }
        }
        else {
            if (imgModel.height > KScaleWidth(224.0)) {
                height = KScaleWidth(224.0);
            }
            else {
                height = imgModel.height;
            }
        }
    }
    return height + KScaleWidth(20.0);
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
